<template>
  <div class="activity-management">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <h1 class="page-title">活动管理</h1>
        <p class="page-subtitle">管理您创建的所有活动</p>
      </div>
      <div class="header-actions">
        <el-button type="primary" @click="goToCreateActivity">
          <el-icon><Plus /></el-icon>
          创建活动
        </el-button>
      </div>
    </div>

    <!-- 统计卡片 -->
    <el-row :gutter="20" class="stats-row">
      <el-col :xs="12" :sm="6">
        <el-card class="stat-card" shadow="hover">
          <div class="stat-content">
            <div class="stat-number">{{ stats.total }}</div>
            <div class="stat-label">总活动</div>
          </div>
          <el-icon class="stat-icon"><Calendar /></el-icon>
        </el-card>
      </el-col>
      <el-col :xs="12" :sm="6">
        <el-card class="stat-card" shadow="hover">
          <div class="stat-content">
            <div class="stat-number">{{ stats.published }}</div>
            <div class="stat-label">已发布</div>
          </div>
          <el-icon class="stat-icon published"><Check /></el-icon>
        </el-card>
      </el-col>
      <el-col :xs="12" :sm="6">
        <el-card class="stat-card" shadow="hover">
          <div class="stat-content">
            <div class="stat-number">{{ stats.draft }}</div>
            <div class="stat-label">草稿</div>
          </div>
          <el-icon class="stat-icon draft"><Edit /></el-icon>
        </el-card>
      </el-col>
      <el-col :xs="12" :sm="6">
        <el-card class="stat-card" shadow="hover">
          <div class="stat-content">
            <div class="stat-number">{{ stats.ended }}</div>
            <div class="stat-label">已结束</div>
          </div>
          <el-icon class="stat-icon ended"><Clock /></el-icon>
        </el-card>
      </el-col>
    </el-row>

    <!-- 搜索和筛选 -->
    <el-card class="filter-card">
      <el-form :model="filters" inline class="filter-form">
        <el-form-item label="关键词">
          <el-input
            v-model="filters.keyword"
            placeholder="搜索活动标题或描述"
            clearable
            style="width: 250px"
            @keyup.enter="loadActivities"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        
        <el-form-item label="状态">
          <el-select v-model="filters.status" placeholder="选择状态" clearable style="width: 150px">
            <el-option label="全部" value="" />
            <el-option label="草稿" value="draft" />
            <el-option label="已发布" value="published" />
            <el-option label="进行中" value="ongoing" />
            <el-option label="已结束" value="ended" />
            <el-option label="已取消" value="cancelled" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="类型">
          <el-select v-model="filters.type" placeholder="选择类型" clearable style="width: 150px">
            <el-option label="全部" value="" />
            <el-option label="学术讲座" value="lecture" />
            <el-option label="文体活动" value="sports" />
            <el-option label="社团活动" value="club" />
            <el-option label="志愿服务" value="volunteer" />
            <el-option label="实践活动" value="practice" />
            <el-option label="其他" value="other" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="创建时间">
          <el-date-picker
            v-model="filters.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            style="width: 240px"
          />
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="loadActivities">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="resetFilters">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 活动列表 -->
    <el-card class="list-card">
      <template #header>
        <div class="list-header">
          <div class="header-title">
            <span>活动列表</span>
            <el-tag v-if="pagination.total > 0" type="info" size="small">
              共 {{ pagination.total }} 个活动
            </el-tag>
          </div>
          <div class="header-actions">
            <el-button-group>
              <el-button 
                :type="viewMode === 'card' ? 'primary' : ''"
                @click="viewMode = 'card'"
              >
                <el-icon><Grid /></el-icon>
              </el-button>
              <el-button 
                :type="viewMode === 'list' ? 'primary' : ''"
                @click="viewMode = 'list'"
              >
                <el-icon><List /></el-icon>
              </el-button>
            </el-button-group>
          </div>
        </div>
      </template>
      
      <!-- 加载状态 -->
      <div v-if="loading" class="loading-container">
        <el-skeleton :rows="5" animated />
      </div>
      
      <!-- 空状态 -->
      <div v-else-if="activities.length === 0" class="empty-container">
        <el-empty description="暂无活动">
          <el-button type="primary" @click="goToCreateActivity">
            创建第一个活动
          </el-button>
        </el-empty>
      </div>
      
      <!-- 卡片视图 -->
      <div v-else-if="viewMode === 'card'" class="card-view">
        <el-row :gutter="20">
          <el-col 
            v-for="activity in activities" 
            :key="activity.id"
            :xs="24" 
            :sm="12" 
            :md="8" 
            :lg="6"
          >
            <div class="activity-card" @click="goToActivityDetail(activity.id)">
              <div class="card-header">
                <div class="activity-status">
                  <el-tag :type="getStatusType(activity.status)" size="small">
                    {{ getStatusText(activity.status) }}
                  </el-tag>
                </div>
                <el-dropdown @command="handleCommand" trigger="click">
                  <el-button type="text" size="small">
                    <el-icon><MoreFilled /></el-icon>
                  </el-button>
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item :command="{ action: 'view', id: activity.id }">
                        <el-icon><View /></el-icon>
                        查看详情
                      </el-dropdown-item>
                      <el-dropdown-item :command="{ action: 'edit', id: activity.id }">
                        <el-icon><Edit /></el-icon>
                        编辑活动
                      </el-dropdown-item>
                      <el-dropdown-item 
                        v-if="activity.status === 'draft'"
                        :command="{ action: 'publish', id: activity.id }"
                      >
                        <el-icon><Check /></el-icon>
                        发布活动
                      </el-dropdown-item>
                      <el-dropdown-item 
                        v-if="['published', 'ongoing'].includes(activity.status)"
                        :command="{ action: 'cancel', id: activity.id }"
                        divided
                      >
                        <el-icon><Close /></el-icon>
                        取消活动
                      </el-dropdown-item>
                      <el-dropdown-item 
                        :command="{ action: 'delete', id: activity.id }"
                        divided
                      >
                        <el-icon><Delete /></el-icon>
                        删除活动
                      </el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </div>
              
              <div class="card-content">
                <h3 class="activity-title">{{ activity.title }}</h3>
                <p class="activity-description">{{ activity.description }}</p>
                
                <div class="activity-meta">
                  <div class="meta-item">
                    <el-icon><Clock /></el-icon>
                    <span>{{ formatDate(activity.startTime, 'MM-DD HH:mm') }}</span>
                  </div>
                  <div class="meta-item">
                    <el-icon><Location /></el-icon>
                    <span>{{ activity.location }}</span>
                  </div>
                  <div class="meta-item">
                    <el-icon><User /></el-icon>
                    <span>{{ activity.currentParticipants || 0 }}/{{ activity.maxParticipants || '不限' }}</span>
                  </div>
                </div>
              </div>
              
              <div class="card-footer">
                <div class="activity-type">
                  <el-tag size="small">{{ getTypeText(activity.type) }}</el-tag>
                </div>
                <div class="activity-time">
                  {{ formatDate(activity.createTime, 'MM-DD') }}
                </div>
              </div>
            </div>
          </el-col>
        </el-row>
      </div>
      
      <!-- 列表视图 -->
      <div v-else class="list-view">
        <el-table :data="activities" style="width: 100%">
          <el-table-column prop="title" label="活动标题" min-width="200">
            <template #default="{ row }">
              <div class="title-cell">
                <span class="title-text" @click="goToActivityDetail(row.id)">{{ row.title }}</span>
                <el-tag :type="getStatusType(row.status)" size="small">
                  {{ getStatusText(row.status) }}
                </el-tag>
              </div>
            </template>
          </el-table-column>
          
          <el-table-column prop="type" label="类型" width="100">
            <template #default="{ row }">
              <el-tag size="small">{{ getTypeText(row.type) }}</el-tag>
            </template>
          </el-table-column>
          
          <el-table-column prop="startTime" label="开始时间" width="150">
            <template #default="{ row }">
              {{ formatDate(row.startTime, 'MM-DD HH:mm') }}
            </template>
          </el-table-column>
          
          <el-table-column prop="location" label="地点" width="150" show-overflow-tooltip />
          
          <el-table-column label="参与人数" width="100">
            <template #default="{ row }">
              {{ row.currentParticipants || 0 }}/{{ row.maxParticipants || '不限' }}
            </template>
          </el-table-column>
          
          <el-table-column prop="createTime" label="创建时间" width="120">
            <template #default="{ row }">
              {{ formatDate(row.createTime, 'MM-DD') }}
            </template>
          </el-table-column>
          
          <el-table-column label="操作" width="200" fixed="right">
            <template #default="{ row }">
              <el-button type="primary" size="small" text @click="goToActivityDetail(row.id)">
                查看
              </el-button>
              <el-button type="primary" size="small" text @click="editActivity(row.id)">
                编辑
              </el-button>
              <el-button 
                v-if="row.status === 'draft'"
                type="success" 
                size="small" 
                text 
                @click="publishActivity(row.id)"
              >
                发布
              </el-button>
              <el-button 
                v-if="['published', 'ongoing'].includes(row.status)"
                type="warning" 
                size="small" 
                text 
                @click="cancelActivity(row.id)"
              >
                取消
              </el-button>
              <el-button 
                type="danger" 
                size="small" 
                text 
                @click="deleteActivity(row.id)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      
      <!-- 分页 -->
      <div v-if="activities.length > 0" class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="loadActivities"
          @current-change="loadActivities"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { formatDate } from '@/utils'
import { ElMessage, ElMessageBox } from 'element-plus'
import api from '@/utils/api'
import {
  Plus,
  Calendar,
  Check,
  Edit,
  Clock,
  Search,
  Refresh,
  Grid,
  List,
  MoreFilled,
  View,
  Close,
  Delete,
  Location,
  User
} from '@element-plus/icons-vue'

const router = useRouter()

const loading = ref(false)
const viewMode = ref('card')

const stats = reactive({
  total: 0,
  published: 0,
  draft: 0,
  ended: 0
})

const filters = reactive({
  keyword: '',
  status: '',
  type: '',
  dateRange: null
})

const pagination = reactive({
  current: 1,
  size: 20,
  total: 0
})

const activities = ref([])

const getStatusType = (status) => {
  const typeMap = {
    draft: 'info',
    published: 'success',
    ongoing: 'warning',
    ended: '',
    cancelled: 'danger'
  }
  return typeMap[status] || ''
}

const getStatusText = (status) => {
  const textMap = {
    draft: '草稿',
    published: '已发布',
    ongoing: '进行中',
    ended: '已结束',
    cancelled: '已取消'
  }
  return textMap[status] || status
}

const getTypeText = (type) => {
  const textMap = {
    lecture: '学术讲座',
    sports: '文体活动',
    club: '社团活动',
    volunteer: '志愿服务',
    practice: '实践活动',
    other: '其他'
  }
  return textMap[type] || type
}

const loadStats = async () => {
  try {
    const response = await api.get('/organizer/activities/stats')
    const data = response.data.data
    
    Object.assign(stats, data)
    
  } catch (error) {
    console.error('加载统计数据失败:', error)
  }
}

const loadActivities = async () => {
  try {
    loading.value = true
    
    const params = {
      page: pagination.current - 1,
      size: pagination.size,
      ...filters
    }
    
    // 处理日期范围
    if (filters.dateRange && filters.dateRange.length === 2) {
      params.startDate = filters.dateRange[0]
      params.endDate = filters.dateRange[1]
    }
    
    const response = await api.get('/organizer/activities', { params })
    const data = response.data.data
    
    activities.value = data.data || []
    pagination.total = data.total || 0
    
  } catch (error) {
    console.error('加载活动列表失败:', error)
    ElMessage.error('加载活动列表失败')
  } finally {
    loading.value = false
  }
}

const resetFilters = () => {
  Object.assign(filters, {
    keyword: '',
    status: '',
    type: '',
    dateRange: null
  })
  pagination.current = 1
  loadActivities()
}

const goToCreateActivity = () => {
  router.push('/organizer/activities/create')
}

const goToActivityDetail = (id) => {
  router.push(`/organizer/activities/${id}`)
}

const editActivity = (id) => {
  router.push(`/organizer/activities/${id}/edit`)
}

const handleCommand = (command) => {
  const { action, id } = command
  
  switch (action) {
    case 'view':
      goToActivityDetail(id)
      break
    case 'edit':
      editActivity(id)
      break
    case 'publish':
      publishActivity(id)
      break
    case 'cancel':
      cancelActivity(id)
      break
    case 'delete':
      deleteActivity(id)
      break
  }
}

const publishActivity = async (id) => {
  try {
    await ElMessageBox.confirm(
      '确定要发布这个活动吗？发布后学生就可以看到并报名参加。',
      '发布活动',
      {
        confirmButtonText: '确定发布',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await api.put(`/organizer/activities/${id}/publish`)
    
    ElMessage.success('活动发布成功')
    loadActivities()
    loadStats()
    
  } catch (error) {
    if (error !== 'cancel') {
      console.error('发布活动失败:', error)
      ElMessage.error('发布活动失败')
    }
  }
}

const cancelActivity = async (id) => {
  try {
    await ElMessageBox.confirm(
      '确定要取消这个活动吗？取消后已报名的学生将收到通知。',
      '取消活动',
      {
        confirmButtonText: '确定取消',
        cancelButtonText: '不取消',
        type: 'warning'
      }
    )
    
    await api.put(`/organizer/activities/${id}/cancel`)
    
    ElMessage.success('活动已取消')
    loadActivities()
    loadStats()
    
  } catch (error) {
    if (error !== 'cancel') {
      console.error('取消活动失败:', error)
      ElMessage.error('取消活动失败')
    }
  }
}

const deleteActivity = async (id) => {
  try {
    await ElMessageBox.confirm(
      '确定要删除这个活动吗？删除后无法恢复，请谨慎操作。',
      '删除活动',
      {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'error'
      }
    )
    
    await api.delete(`/organizer/activities/${id}`)
    
    ElMessage.success('活动删除成功')
    loadActivities()
    loadStats()
    
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除活动失败:', error)
      ElMessage.error('删除活动失败')
    }
  }
}

onMounted(() => {
  loadStats()
  loadActivities()
})
</script>

<style scoped>
.activity-management {
  max-width: 1400px;
  margin: 0 auto;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding: 24px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.header-content {
  flex: 1;
}

.page-title {
  font-size: 24px;
  font-weight: 700;
  color: #303133;
  margin: 0 0 8px 0;
}

.page-subtitle {
  font-size: 14px;
  color: #606266;
  margin: 0;
}

.header-actions {
  margin-left: 20px;
}

.stats-row {
  margin-bottom: 24px;
}

.stat-card {
  height: 100px;
  cursor: pointer;
  transition: transform 0.3s ease;
}

.stat-card:hover {
  transform: translateY(-2px);
}

.stat-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 100%;
}

.stat-number {
  font-size: 24px;
  font-weight: 700;
  color: #303133;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 14px;
  color: #909399;
}

.stat-icon {
  font-size: 28px;
  opacity: 0.3;
  color: #409eff;
}

.stat-icon.published {
  color: #67c23a;
}

.stat-icon.draft {
  color: #e6a23c;
}

.stat-icon.ended {
  color: #909399;
}

.filter-card {
  margin-bottom: 20px;
}

.filter-form {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
}

.list-card {
  min-height: 400px;
}

.list-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-title {
  display: flex;
  align-items: center;
  gap: 12px;
  font-weight: 600;
  color: #303133;
}

.loading-container,
.empty-container {
  padding: 40px;
  text-align: center;
}

.card-view {
  margin-bottom: 20px;
}

.activity-card {
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  padding: 16px;
  margin-bottom: 20px;
  cursor: pointer;
  transition: all 0.3s ease;
  height: 280px;
  display: flex;
  flex-direction: column;
}

.activity-card:hover {
  border-color: #409eff;
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.15);
  transform: translateY(-2px);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.card-content {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.activity-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  margin: 0 0 8px 0;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.activity-description {
  font-size: 14px;
  color: #606266;
  margin: 0 0 12px 0;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  flex: 1;
}

.activity-meta {
  display: flex;
  flex-direction: column;
  gap: 6px;
  margin-bottom: 12px;
}

.meta-item {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 12px;
  color: #909399;
}

.card-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-top: 12px;
  border-top: 1px solid #f0f0f0;
}

.activity-time {
  font-size: 12px;
  color: #909399;
}

.list-view {
  margin-bottom: 20px;
}

.title-cell {
  display: flex;
  align-items: center;
  gap: 8px;
}

.title-text {
  cursor: pointer;
  color: #409eff;
  text-decoration: none;
}

.title-text:hover {
  text-decoration: underline;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #e4e7ed;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    gap: 16px;
    text-align: center;
  }
  
  .header-actions {
    margin-left: 0;
  }
  
  .filter-form {
    flex-direction: column;
  }
  
  .filter-form .el-form-item {
    margin-right: 0;
    margin-bottom: 16px;
  }
  
  .list-header {
    flex-direction: column;
    gap: 12px;
  }
  
  .activity-card {
    height: auto;
    min-height: 200px;
  }
  
  .activity-meta {
    flex-direction: column;
  }
}
</style>